<?php

class Reward extends Controller {
	
	public $images_passed = array();

	public function image($sex = "male") {
		
		$sex = strtolower($sex); $sex = $sex=="female" ? "female" : "male";
		
		$referer = preg_replace('/\/+$/', '', $_SERVER['HTTP_REFERER']);
		$accept = $_SERVER['HTTP_ACCEPT'];
		$server = $_SERVER['SERVER_NAME'];
		
		$condition1 = $referer=="http://$server";
		$condition2 = preg_match('/^image\//',$accept);
		$condition = $condition1 && $condition2;
		if ($condition) {
			
			$this->images_passed = &$_SESSION["images_passed"];
			
			$dirname = "img/rewards/$sex/";
			$dir = opendir($dirname);
			if(!$dir) {
				$this->_error("Error opening $dirname");
			}
			$images = array();
			while ($f = readdir($dir)) {
				if(!preg_match('/^\.+$/',$f) && preg_match('/\.jpg$|\.jpeg$|\.gif$|\.png$|\.bmp$/i', $f)) {
					$images[] = $f;
				}
			}
			
			if (count($this->images_passed)==count($images)) {
				$this->images_passed = array($this->images_passed[count($this->images_passed)-1]);
			}
			
			while(1) {
				$rnd = rand(0,count($images)-1);
				$image = $images[$rnd];
				if(!in_array($image,$this->images_passed)) {
					$this->images_passed[] = $image;
					break;
				}
			}
			
			$ext = strtolower(substr($image,strrpos($image,".")+1));
			$ext = $ext=="jpg" ? "jpeg" : $ext;
			
			eval('$img = imagecreatefrom'.$ext.'("'.$dirname.$image.'");');
			
			header("Content-Type: image/$ext");
			eval('image'.$ext.'($img);');
		}else{
			$this->_error("Image not found.");
		}
	}
	
	private function _error($text) {
		header("Content-Type: image/gif");
		$img = imagecreatetruecolor(640,480);
		imagefilledrectangle($img,0,0,640,480,imagecolorallocate($img,200,200,200));
		imagestring($img,10,230,220,$text,imagecolorallocate($img,0,0,0));
		imagegif($img);
		die();
	}
	
}

?>